#include "msg.h"
#include "boot.h"
#include "usart.h"
#include "protocol.h"
/**************************************
	主要固件升级的协议部分
**************************************/

MSG_t msg;

uint8_t msgStat=0;  						// 接收消息状态机



// 消息帧解析，返回1：解析成功   0:解析失败
uint8_t msgParse(uint8_t data,MSG_t *msg)
{
	uint8_t rq=0;
	static uint16_t msgIndex=0,checkSum=0;
	
	switch(++msgStat)
	{
			case UPDATA_MSG_HEAD:
			{
					if(data==UPDATA_HEAD)
					{
							msg->head = data;
							checkSum = 0;
							msgIndex = 0;
							msg->len =0;
					}
					else    msgStat = UPDATA_MSG_IDEL;
					break;
			}
			case UPDATA_MSG_MSGTYPE:     
			{
					msg->type = data;
					checkSum += data;
					break;
			}
			case UPDATA_MSG_LEN:
			{
				 checkSum += data;
				 if((data & 0x80)!=0 && msg->len==0){
				 		msg->len = (data & 0x7f)*128;
				 		msgStat = UPDATA_MSG_MSGTYPE;
				 }else{
				 		msg->len = msg->len+data;
				 		if(msg->len==0)   // 没有消息内容
				 		{
				 				msgStat = UPDATA_MSG_PAYLOAD;
				 		}
				 }
				 break;
			}
			case UPDATA_MSG_PAYLOAD:
			{
					msg->buff[msgIndex] = data;
					checkSum += data;
					msgIndex++;
					if(msg->len==msgIndex)      msgStat = UPDATA_MSG_PAYLOAD;
					else            					  msgStat = UPDATA_MSG_LEN;
					break;
			}
			case UPDATA_MSG_CKH:
			{
					msg->ckH = data;
					break;
			}
			case UPDATA_MSG_CKL:
			{
					msg->ckL = data;
					if(((checkSum>>8) & 0x00ff)== msg->ckH && (checkSum & 0x00ff)== msg->ckL)
					{
						 rq = 1; // 校验成功
					}
					else {
							rq = 0;  // 校验失败
					}
					msgStat = UPDATA_MSG_IDEL;
					break;
			}
			default:
			{
					msgStat = UPDATA_MSG_IDEL;
					break;
			}
	}
	msg->stat = rq;
	return rq;
}



// bin文件获取指令
void binRequest(uint16_t index)
{
	//0xFE,0x04, 0x01, 0x05, 0x00, 0x0A
	//0xFE,0x04, 0x02, 0x01, 0x02, 0x00, 0x09
	uint16_t sum;
	uint8_t buf[7] = {0xFE ,MSG_FIRMWARE_REQ};
	if(index>127){
		buf[2] = 2;
		buf[3] = (index>>8)&0x00ff;
		buf[4] = index&0x00ff;
		sum = buf[1]+buf[2]+buf[3]+buf[4];
		buf[5] = (sum>>8)&0x00ff;
		buf[6] = sum&0x00ff;	
		USART_SendBuf(USART1, buf, sizeof(buf));
	}
	else{
		buf[2] = 1;
		buf[3] = index&0x00ff;
		sum = buf[1]+buf[2]+buf[3];
		buf[4] = (sum>>8)&0x00ff;
		buf[5] = sum&0x00ff;	
		USART_SendBuf(USART1, buf, 6);
	}
}

// 版本信息请求
void versionRequest(void)
{
	uint8_t buf[5] = {0xFE, 0x02, 0x00,0x00,0x02};
	 USART_SendBuf(USART1, buf, 5);
}

// 更新结束指令,携带最新版本信息
void updateEnd(uint16_t v)
{
	uint16_t checkSum=0;
	uint8_t data[7] = {0xFE, MSG_UPDATE_FINISH, 0x02,0,0,0x00,0x01};
	data[3]= v>>8 &0x00ff;
	data[4]= v & 0x00ff;
	checkSum = data[1]+data[2]+data[3]+data[4];
	data[5]= checkSum>>8 &0x00ff;
	data[6]= checkSum & 0x00ff;

  USART_SendBuf(USART1, data, sizeof(data));
}





